package cn.mw.cmdb.entity;

import cn.mw.cmdb.param.ImportContextParam;
import cn.mw.cmdb.service.impl.CmdbServiceManage;
import cn.mw.cmdb.service.impl.CustomModelServiceImpl;
import cn.mw.cmdb.service.impl.InstanceServiceImpl;
import cn.mw.cmdb.service.impl.InstanceViewImpl;
import cn.mw.components.mongodb.entity.CriteriaOpsType;
import cn.mw.components.mongodb.entity.MPropertyTypeString;
import cn.mw.microMonitorCommon.entity.cmdb.ModelExportDataInfoParam;
import cn.mw.microMonitorCommon.entity.cmdb.MwImportResultParam;
import cn.mw.microMonitorCommon.util.SpringUtils;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static cn.mw.cmdb.service.impl.InstanceViewImpl.*;
import static cn.mw.cmdb.service.impl.InstanceViewImpl.linkDataKey;
import static cn.mw.cmdb.util.ValConvertUtil.intValueConvert;

@Slf4j
public class PropertyTypeString extends PropertyType<PropertyTypeString, String> {
    public static final String ID = MPropertyTypeString.ID;
    public static final String PatternKey = MPropertyTypeString.PatternKey;

    public static final String ValueKey = MPropertyTypeString.ValueKey;

    private static Map<String, Object> map = new HashMap<>();
    private static List<String> finalList = new ArrayList<>();

    private MPropertyTypeString mPropertyTypeString = new MPropertyTypeString();

    public PropertyTypeString() {
        setId(ID);
        setName("字符串");
        setValueTip("请输入字符串");
        setSortNum(1);
    }

    @Override
    public String convertValue(Object value) {
        return null != value ? value.toString().trim() : null;
    }

    public Object convertValue(String propertyId,Object value) {
        String convertValue = null;
        //如果是资产类型，需要特殊处理
        if(MW_ASSET_TYPE_Key.equals(propertyId) && value != null){
            String valStr = strValueConvert(value);
            String[] splitSub = valStr.split("/");
            if(splitSub!=null && splitSub.length > 0){
                convertValue = splitSub[splitSub.length - 1];
            }
        }
        return convertValue;
    }

    @Override
    public Criteria doCriteria(CriteriaOpsType opsType, String name, Object value) {
        //修改人，创建人查询，使用负责人属性
        if(modifierPath.equals(name) || createrPath.equals(name) ){
            PropertyType typeUser = new PropertyTypeUser();
            return typeUser.doCriteria(opsType, name, value);
        }
        return mPropertyTypeString.doCriteria(opsType, name, value);
    }

    @Override
    public Object readValue(Object val, Map<String, Object> context) {
        if (val != null && val instanceof String) {
            String jsonString = strValueConvert(val);
            return jsonString;
        }
        return null;
    }

    @Override
    public CriteriaOpsType getDefaultCriteriaOpsType() {
        return CriteriaOpsType.like;
    }

    @Override
    public PropertyTypeString newObj() {
        return new PropertyTypeString();
    }

    @Override
    public boolean tableHeaderInfo(Map ms, PropertyInfo propertyInfo, List<String> labelNames, List<String> labelId) throws Exception {
        //导出表头数据时，表头字段的id和名称不能同时重复
        if ((labelId != null && !labelId.contains(propertyInfo.getId())) && (labelNames != null && !labelNames.contains(ms.get(nameKey)))) {
            if (propertyInfo.getPropertyTypeRef() != null) {
                String id1 = propertyInfo.getId();
                labelId.add(propertyInfo.getId());
                if(MW_ASSET_TYPE_Key.equals(id1)){
                    CmdbServiceManage cmdbServiceManage = SpringUtils.getBean(CmdbServiceManage.class);
                    CustomModelServiceImpl modelService = (CustomModelServiceImpl) cmdbServiceManage.getModelService(CustomModelServiceImpl.ID);
                    List<String> pathNames = modelService.getAllModelPathName(null);
                    ms.put(selectDataKey, pathNames);
                }
                return true;
            }
        }
        return false;
    }


    @Override
    public boolean validateValue(Object value, PropertyTypeRef propertyTypeRef) throws Exception {
        if (value instanceof String) {
            Map<String, Object> context = propertyTypeRef.getContext();
            if (null != context && context.get(PatternKey) != null) {
                String pstr = context.get(PatternKey).toString();
                if (StringUtils.hasText(pstr)) {
                    Pattern pattern = Pattern.compile(pstr);
                    Matcher matcher = pattern.matcher(value.toString());
                    if (!matcher.matches()) {
                        return false;
                    }
                }
            }
        }
        return super.validateValue(value, propertyTypeRef);
    }

    @Override
    public void refresh() {
        finalList.clear();
    }


    @Override
    public Object getDataValue(ImportContextParam contextParam) {
        MwImportResultParam resultParam = new MwImportResultParam();
        String message = "";
        ModelExportDataInfoParam importParam = contextParam.getParam();
        String propertyId = importParam.getPropertyId();
        //属性名称
        String tableName = importParam.getTableName();
        Object cellValue = importParam.getCellValue();
        Map<String, Object> matchMap = new HashMap<>();
        boolean isDefaultFlag = false;
        //数值类型为空字符串，默认为0
        if (Strings.isNullOrEmpty(strValueConvert(cellValue))) {
            //空字符串
            if (matchMap != null && matchMap.get(ValueKey) != null) {
                Object obj = matchMap.get(ValueKey);
                isDefaultFlag = true;
                cellValue = obj;
                importParam.setCellValue(obj);
            }
        }
        //是否默认值提示
        String prefixStr = prefixStrKey;
        if (isDefaultFlag) {
            prefixStr = defaultPrefixStrKey;
        }
        importCheckInfo(resultParam, contextParam, matchMap);

        if (resultParam != null) {
            message += resultParam.getMessage();

            if (matchMap != null && matchMap.size() > 0) {
                //长度校验
                int lengthNum = intValueConvert(matchMap.get(lengthNumKey)) == 0 ? defaultStrMaxlength : intValueConvert(matchMap.get(lengthNumKey));
                String valueStr = strValueConvert(cellValue);
                if (valueStr.length() > lengthNum) {
                    message += tableName + prefixStr + valueStr + "]长度超过限制[" + lengthNum + "]";
                }
                //正则校验
                String patternStr = strValueConvert(matchMap.get(patternKey));
                if (StringUtils.hasText(patternStr)) {
                    Pattern pattern = Pattern.compile(patternStr);
                    Matcher matcher = pattern.matcher(valueStr);
                    if (!matcher.find()) {
                        message += tableName + prefixStr + valueStr + "]内容不匹配正则表达式[" + patternStr + "]";
                    }
                }
            }
            resultParam.setMessage(message);
            log.info("字符串类型::");
            resultParam.setCellValue(cellValue);
        }
        return resultParam;
    }
}
